<template>
	<view @click="closeRedPacked">
		<view v-if="packerState != 3" class="packer-box flex-column">
			<view class="packer-bg anim-ease-in" :class="{ 'anim-fade-out': packerState == 2 }"></view>
			<view class="packer-bottom-box anim-ease-in" :class="{ 'anim-out-bottom': packerState == 2 }">
				<view class="arc-bottom-edge"></view>
				<view class="packer-bottom-bg"></view>
			</view>
			<view class="packer-top-box anim-ease-in" :class="{ 'anim-out-top': packerState == 2 }">
				<view class="flex-row sender-info">
					<!-- 红包已领完时显示 “手慢了” -->
					<view v-if="packerState === 10">手慢了，红包派完了</view>
					<!-- 其他状态下显示发红包者 -->
					<view v-else>{{username}}发出的红包</view>
				</view>

				<!-- 问候语 -->
				<view class="packer-greeting double-text" v-if="packerState !== 10">
					{{ messageData.meno || '恭喜发财，大吉大利' }}
				</view>

				<view class="arc-edge"></view>

				<!-- packerState == 1：转动的开按钮 -->
				<view v-if="packerState == 1" class="anim-rotate packer-btn-pos">
					<view class="packer-btn" style="transform: translateZ(-4px);">開</view>
					<view class="packer-btn-middle" v-for="(item, index) in 7" :key="index"
						:style="{transform: `translateZ(${index - 3}px)`}"></view>
					<view class="packer-btn packer-btn-front">開</view>
				</view>

				<!-- 红包已领完显示 “看看大家的手气” 按钮 -->
				<view v-else-if="packerState === 10" class="packer-btn packer-btn-pos" @click.stop="openPacker">
					看看大家的手气
				</view>

				<!-- 普通“開”按钮 -->
				<view v-else class="packer-btn packer-btn-pos" @click.stop="openPacker">
					開
				</view>
			</view>
		</view>
	</view>
</template>


<script>
	import Config from "@/common/config.js"; // 本地配置数据
	export default {
		name: "red-packed",
		props: ['username', 'id', 'value'],
		data() {
			return {
				packerState: 0,
				messageData: {} // 存储解析后的 message 对象
			};
		},
		created() {
			if (typeof this.value.message === 'string') {
				try {
					this.messageData = JSON.parse(this.value.message);
					console.log('message 解析:', this.messageData);
				} catch (e) {
					console.error('message 解析失败', e);
				}
			} else {
				this.messageData = this.value.message || {};
			}
		},
		methods: {
			onAnimationEnd() {
				console.log("动画执行完毕");

			},
			closeRedPacked() {
				this.$emit("closeRedPacked")
			},
			openPacker() {
				// 加载数据，触发硬币旋转动画
				console.log('红包内容：', this.value);
				this.packerState = 1;

				// 接口请求，动画进行时并发起红包领取
				this.receiveRedpacket(this.value);

				let data = JSON.parse(this.value.message);
				const isGroup = data.isGroup;
				console.log(data);
				console.log(JSON.stringify(data, null, 2)); // 美化输出
				let redPackedId = '';
				if (isGroup) {
					redPackedId = data.redPackedId || '';
				} else {
					redPackedId = data.message.redPackedId || '';
				}
				// const redPackedId = data.message.redPackedId;
				console.log("redPackedId:", redPackedId);

				this.request(() => {
					// 调用抢红包接口成功，触发开红包动画
					this.packerState = 2;

					// 开红包动画结束后，移除相关节点
					setTimeout(() => {
						this.packerState = 3;
						this.$emit("closeRedPacked");

						const url = isGroup ?
							`/pages/openredpacked/openredpackeds?id=${this.id}&redPackedId=${redPackedId}` :
							`/pages/openredpacked/openredpacked?id=${this.id}&redPackedId=${redPackedId}`;

						uni.navigateTo({
							url
						});
					}, 500);
				});
			},

			receiveRedpacket(value) {
				const userinfo = uni.getStorageSync('userinfo');
				const userToken = userinfo.token;
				const userId = userinfo.user_id;
				console.log("value:" + value); // 美化输出
				console.log(JSON.stringify(value, null, 2)); // 美化输出
				let data = value.message;
				try {
					data = JSON.parse(data);
				} catch (e) {
					console.error("红包 message JSON 解析失败", e);
					return;
				}
				console.log(data)
				const messageId = value.id; // 获取消息id
				if (data.isGroup) {
					this.$u.post(`https://${Config.baseUrl}/api/Redpacket/claimRedpacket?im_tourists_token=` + userToken, {
						user_id: userId,
						redpacket_id: data.redPackedId,
						messageId: messageId,
					}).then(res => {
						if (res.status === 'success') {
							console.log("群红包领取成功", res);
							uni.setStorageSync('group_redpacket_claim', {
								redpacket_id: data.redPackedId,
								amount_received: res.amount_received
							});
							this.markAsUsed(value);
						} else {
							this.$refs.uToast?.show({
								title: res.message || '领取失败',
								type: 'error'
							});
						}
					}).catch(err => {
						console.error("领取群红包出错", err);
						this.$refs.uToast?.show({
							title: '网络异常，请重试',
							type: 'error'
						});
					});
				} else {
					this.$u.post(`https://${Config.baseUrl}/api/Redpacket/receiveRedpacket?im_tourists_token=` +
						userToken, {
							id: data.message.redPackedId
						}).then(res => {
						console.log("单个红包领取成功", res);
						uni.setStorageSync('redpackedlog', res.data);
						this.markAsUsed(value);
					});
				}
				// this.$emit('openRedpacked');
			},
			markAsUsed(value) {
				try {
					const parsedMessage = JSON.parse(value.message || '{}');

					const userinfo = uni.getStorageSync('userinfo');
					const currentUserId = String(userinfo?.user_id || '');

					if (!parsedMessage.received_users) {
						parsedMessage.received_users = [];
					} else if (typeof parsedMessage.received_users === 'string') {
						parsedMessage.received_users = parsedMessage.received_users.split(',');
					}

					// 添加当前用户 ID，去重
					if (!parsedMessage.received_users.includes(currentUserId)) {
						parsedMessage.received_users.push(currentUserId);
					}

					value.message = JSON.stringify(parsedMessage);

					// 触发状态更新事件
					this.$emit('update-status', {
						messageId: value.id, // 消息唯一标识
						receivedUsers: parsedMessage.received_users
					});
				} catch (e) {
					console.error("解析 message 出错", e);
				}
			},

			request(success) {
				setTimeout(() => {
					success()
				}, 3000);
			}
		}
	}
</script>

<style>
	.flex-row {
		display: flex;
		flex-direction: row;
		position: relative;
	}

	.flex-column {
		display: flex;
		flex-direction: column;
		position: relative;
	}

	.packer-box {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 99;
		color: rgb(235, 205, 153);
		padding: 60rpx;
	}

	.packer-bg {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
	}

	.packer-top-box {
		width: 600rpx;
		background-color: rgb(244, 94, 77);
		text-align: center;
		margin: auto;
		transform: translateY(-160rpx);
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
		position: relative;
	}

	.sender-info {
		margin-top: 200rpx;
		justify-content: center;
		line-height: 60rpx;
		font-size: 36rpx;
	}

	.sender-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 10rpx;
		background-color: #fff;
		margin-right: 10rpx;
	}

	.packer-greeting {
		font-size: 48rpx;
		line-height: 60rpx;
		height: 120rpx;
		margin: 40rpx 30rpx 200rpx;
	}

	.arc-edge {
		position: relative;
	}

	.arc-edge::after {
		width: 100%;
		height: 200rpx;
		position: absolute;
		left: 0;
		top: -100rpx;
		z-index: 9;
		content: '';
		border-radius: 50%;
		background-color: rgb(244, 94, 77);
		box-shadow: 0 6rpx 6rpx 0 rgba(0, 0, 0, 0.1);
	}

	.packer-bottom-box {
		transform: translate(-50%, 0);
		width: 600rpx;
		height: 360rpx;
		border-bottom-left-radius: 30rpx;
		border-bottom-right-radius: 30rpx;
		overflow: hidden;
		position: absolute;
		bottom: calc(50% - 440rpx);
		left: 50%;
	}

	.anim-ease-in {
		animation-duration: 0.5s;
		animation-timing-function: ease-in;
		animation-fill-mode: forwards;
	}

	.anim-out-top {
		animation-name: slideOutTop;
	}

	.anim-out-bottom {
		animation-name: slideOutBottom;
	}

	.anim-fade-out {
		animation-name: fadeOut;
	}

	@keyframes fadeOut {
		from {
			opacity: 1;
		}

		to {
			opacity: 0;
		}
	}

	@keyframes slideOutTop {
		from {
			transform: translateY(-160rpx);
		}

		to {
			transform: translateY(-200%);
		}
	}

	@keyframes slideOutBottom {
		from {
			transform: translate(-50%, 0);
		}

		to {
			transform: translate(-50%, 200%);
		}
	}

	.arc-bottom-edge {
		position: relative;
	}

	.arc-bottom-edge::after {
		width: 120%;
		height: 200rpx;
		position: absolute;
		left: -10%;
		top: -100rpx;
		z-index: 8;
		content: '';
		border-radius: 50%;
		box-shadow: 0 60rpx 0 0 rgb(242, 85, 66);
	}

	.packer-bottom-bg {
		background-color: rgb(242, 85, 66);
		height: 280rpx;
		margin-top: 100rpx;
	}

	.packer-btn {
		border-radius: 50%;
		width: 200rpx;
		height: 200rpx;
		line-height: 200rpx;
		font-size: 80rpx;
		text-align: center;
		color: #333;
		background-color: rgb(235, 205, 153);
		box-shadow: 0 0 6rpx 0 rgba(0, 0, 0, 0.1);
	}

	.packer-btn-pos {
		transform: translateX(-50%);
		position: absolute;
		left: 50%;
		z-index: 10;
		bottom: -200rpx;
	}

	.packer-btn-front {
		position: absolute;
		top: 0;
		transform: translateZ(4px);
	}

	.packer-btn-middle {
		position: absolute;
		top: 0;
		border-radius: 50%;
		width: 200rpx;
		height: 200rpx;
		background-color: rgb(235, 180, 120);
	}

	.anim-rotate {
		margin-left: -100rpx;
		transform-style: preserve-3d;
		animation: rotate 1s linear infinite;
	}

	@keyframes rotate {
		0% {
			transform: rotateY(0deg);
		}

		100% {
			transform: rotateY(360deg);
		}
	}
</style>